﻿/* 
 *========================================================================
 * 描述信息 
 *  
 * 作者：w       
 * 时间：2021/4/29 14:26:15 
 * 文件名：NetCapture 
 * CLRVersion：4.0.30319.42000
 * 版本：V1.0.0 
 * 
 * 修改者：           
 * 时间：               
 * 修改说明： 
 *======================================================================== 
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpPcap;
using PacketDotNet;
using PacketDotNet.Utils;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication2
{
    public class NetCapture
    {
        public static void Start()
        {
            CaptureDeviceList devices = CaptureDeviceList.Instance;
            int count = devices.Count;
            for (int i = 0; i < count; i++)
            {
                ICaptureDevice device = devices[i];
                StartCapture ca = new StartCapture(device);
                ca.Start();
            }
        }
        public static void Device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            //获取以太网（Ethernet）的帧
            var ent = PacketDotNet.EthernetPacket.ParsePacket(LinkLayers.Ethernet, e.Packet.Data);
            var ip = ent.PayloadPacket;
            var tcp = ip.PayloadPacket;
            if (tcp != null)
            {
                if (tcp.GetType() == typeof(TcpPacket))
                {
                    var tcp_packet = new TcpPacket(new ByteArraySegment(tcp.Bytes));
                    ThisQueue.Enqueue(new Tuple<ushort, MsgEntity>(tcp_packet.DestinationPort,
                                    new MsgEntity() { DataLength = ent.Bytes.Length, RecevieTime = DateTime.Now.Ticks }));
                }
                else if (tcp.GetType() == typeof(UdpPacket))
                {
                    var udp_packet = new UdpPacket(new ByteArraySegment(tcp.Bytes));
                    ThisQueue.Enqueue(new Tuple<ushort, MsgEntity>(udp_packet.DestinationPort,
                                    new MsgEntity() { DataLength = ent.Bytes.Length, RecevieTime = DateTime.Now.Ticks }));
                }
            }
        }
        public static MsgQueue ThisQueue = new MsgQueue();
    }
}
